package com.ytjj.qmyx.mall.service.impl;

import com.ytjj.common.constants.CopyWriterConstant;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.constants.SysConfigConstants;
import com.ytjj.common.dto.mqdto.OrderRecordDto;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.utils.CopyWriterConfigUtil;
import com.ytjj.common.utils.SysConfigUtil;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.mall.constants.PayModeConstant;
import com.ytjj.qmyx.mall.mapper.OrdersSpecMapper;
import com.ytjj.qmyx.mall.enums.ActivityTypeEnums;
import com.ytjj.qmyx.mall.mapper.ProductActivityMapper;
import com.ytjj.qmyx.mall.mapper.ProductMapper;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.mall.model.request.H5CreateOrderRequest;
import com.ytjj.qmyx.mall.model.response.ProductActivitySpecResponse;
import com.ytjj.qmyx.mall.service.ActivityService;
import com.ytjj.qmyx.mall.service.CreateOrderService;
import com.ytjj.qmyx.mall.service.OrdersService;
import com.ytjj.qmyx.mall.service.YxProductGroupBuyInfoService;
import com.ytjj.qmyx.users.client.UsersClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Optional;

/**
 * h5 活动商品订单
 *
 *
 * @version 1.0
 *
 */
@Service("H5ACTIVITY")
@Slf4j
public class H5OrdersActivityServiceImpl implements CreateOrderService<H5CreateOrderRequest> {

    @Autowired
    private UsersClient usersClient;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private OrdersService ordersService;

    @Resource
    private SysConfigUtil sysConfigUtil;

    @Resource
    private CopyWriterConfigUtil copyWriterConfigUtil;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private ProductActivityMapper productActivityMapper;
    @Autowired
    private YxProductGroupBuyInfoService yxProductGroupBuyInfoService;

    @Resource
    private OrdersSpecMapper ordersSpecMapper;

    @Override
    public Integer createOrder(H5CreateOrderRequest request) {
        Integer userId = null;
        if(StringUtils.isNotEmpty(request.getTel())){
            // 获取用户id 用户服务处理
            userId = usersClient.h5GetUserIdByTel(request.getTel(), request.getChannel(), TokenUtil.getToken());
        }
        // 活动创建订单
        Product activityProductInfo = productMapper.selectByPrimaryKey(request.getProductId());
        Optional.ofNullable(activityProductInfo).orElseThrow(() -> new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.COMMODITY_NOT_EXIST)));

        if (Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.IS_STOCE_VERIFY)) > 0 && activityProductInfo.getStock() <= 0) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.INSUFFICIENT_STOCK));
        }
        ProductActivitySpecResponse activitySpec = activityService.getActivityProductSpecById(request.getProductSpecId());
        if (Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.IS_STOCE_VERIFY)) > 0 && activitySpec.getStock() <= 0) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.INSUFFICIENT_STOCK));
        }
        ProductActivity productActivity = new ProductActivity();
        if (null != activitySpec && null != activitySpec.getActivityId()) {
            productActivity = productActivityMapper.selectByPrimaryKey(activitySpec.getActivityId());
        }
        //如果是拼团活动
        if (ActivityTypeEnums.GROUP_WORK.name().equals(activityProductInfo.getActivityType())) {
            ProductGroupBuyInfo productGroupBuyInfo = yxProductGroupBuyInfoService.queryByProductId(activityProductInfo.getId());
            activitySpec.setPrice(productGroupBuyInfo.getGroupPrice());
        }
        Integer isDirectBuy = 0;
        // 支付方式为 “直接购买” 则取出现价字段
        if(PayModeConstant.ORIGINAL_PRICE.equals(request.getFlag())){
            activitySpec.setPrice(activitySpec.getCurPrice());
            isDirectBuy = 1;
//            if (ActivityTypeEnums.GROUP_WORK.name().equals(activityProductInfo.getActivityType())) {
//                ProductGroupBuyInfo productGroupBuyInfo = yxProductGroupBuyInfoService.queryByProductId(activityProductInfo.getId());
//                activitySpec.setPrice(productGroupBuyInfo.getDirectPrice());
//            }
        }
        //乘商品数量
        BigDecimal originalPrice_new = activityProductInfo.getOriginalPrice();
        BigDecimal price_new = activitySpec.getPrice();
        if (null != request.getProductSum() && request.getProductSum() > 1){
            originalPrice_new = activityProductInfo.getOriginalPrice().multiply(BigDecimal.valueOf(request.getProductSum()));
            price_new = activitySpec.getPrice().multiply(BigDecimal.valueOf(request.getProductSum()));
        }
        // 主订单
        Orders orders = ordersService.saveOrders(userId, request.getTel(),request.getProvince(),request.getCity(),request.getArea(),
                request.getAddress(), request.getUserName(),
                originalPrice_new, price_new,
                request.getOrderSource(),request.getChannel(),TokenUtil.getToken(),"",request.getDomainUrl(),null,null);
        // 明细订单
        OrdersInfo ordersInfo = ordersService.saveOrdersInfo(orders.getId(), activityProductInfo.getId(), activityProductInfo.getProductName(), activityProductInfo.getProductImg(),
                activitySpec.getPrice(), activityProductInfo.getOriginalPrice(), activityProductInfo.getWarehouse(), activityProductInfo.getWarehouseName(),
                activityProductInfo.getWarehouseRule(), request.getSpecialId(), activitySpec.getSkuSpec(), activityProductInfo.getBankerId(), activitySpec.getId(),
                request.getActivityType(), activityProductInfo.getId(), activityProductInfo.getActivityMax(), activityProductInfo.getActivityMin(),
                activityProductInfo.getDescr(),isDirectBuy,request.getPageSourceV2(),null,2,0, productActivity.getCost(),request.getProductSum());
        try {
            //记录订单规格信息
            ProductSpec productSpec = ordersSpecMapper.selectOrderSpec(request.getProductSpecId());
            ordersSpecMapper.insertOrderSpec(productSpec.getSkuSpec(),orders.getId(),productSpec.getPrice(),productSpec.getOriginalPrice(),productSpec.getCostPrice());
        }catch (Exception e){
            log.error("发送到rabbitmq错误",e);
        }
        return orders.getId();
    }

    @Override
    public Integer cartCreateOrder(H5CreateOrderRequest request) {
        return null;
    }
}
